<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { onMounted, onBeforeUnmount, watch, ref, reactive } from 'vue'
import * as echarts from 'echarts'
import { headersStore } from '@/stores/apiHeader'
import { DEFAULT_ECHARTS_FONTSIZE,DIALOG_ECHARTS_FONTSIZE } from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const headerStore = headersStore()
const { language_id } = storeToRefs(headerStore)
const fontSize = dialogInfo.visible ? DIALOG_ECHARTS_FONTSIZE : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()


watch(
  () => props.chartData,
  () => {
    createChart()
  },
  { deep: true }
)

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}

const data = reactive([])
// 算出百分比,填到data里面
const addPercentToData = () => {
  // 将props.chartData.data,存入data里面
  data.splice(0, data.length, ...props.chartData.data)
  // 求出value的和
  let totalValue = 0
  let totalPercent = 0
  // 循环一遍算出totalValue
  for (let i = 0; i < props.chartData.data.length; i++) {
    let theValue = parseFloat(props.chartData.data[i].value.toString())
    totalValue += theValue
  }
  for (let i = 0; i < props.chartData.data.length; i++) {
    // 如果totalValue为0,就不用算百分比了
    if (totalValue == 0) {
      data[i].percent = '0%'
      continue
    }
    let theValue = parseFloat(props.chartData.data[i].value.toString())
    // 算出百分比
    let percent = totalValue == 0 ? 0 : ((theValue || 0) / totalValue) * 100
    // 保留两位小数
    percent = parseFloat(percent.toFixed(2))
    totalPercent += percent
    // 如果是最后一个,并且百分比不到100,就让他等于100
    if (i == props.chartData.data.length - 1) {
      if (totalPercent < 100) {
        percent = 100 - totalPercent + percent
      }
      if (totalPercent > 100) {
        percent = percent - (totalPercent - 100)
      }
      percent = parseFloat(percent.toFixed(2))
    }
    // 将百分比存入data里面
    data[i].percent = percent + '%'
  }
}
var myChart

const createChart = () => {
  if (myChart != null && myChart != '' && myChart != undefined) {
    myChart.dispose() //解决echarts dom已经加载的报错
  }
  myChart = echarts.init(document.getElementById(props.chartData.name))
  addPercentToData()
  const option = {
    // 鼠标放上去的
    tooltip: {
      confine: true,
      trigger: 'item',
      backgroundColor: 'rgba(0,0,0,0.7)', //默认值，提示背景颜色，默认为透明度为0.7的黑色
      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: '#fff', //设置文字颜色
      },
      borderWidth: 0,
      padding: changePixelSize(8),
      formatter: function (params) {
        let target = ''
        let percentStr = ''
        for (let i = 0; i < props.chartData.data.length; i++) {
          if (props.chartData.data[i].name == params.name) {
            target =
              (props.chartData.data[i]?.valueFormat || '') +
              (props.chartData.legend?.suffixHidden
                ? ''
                : props.chartData.data[i]?.suffix)
            percentStr = props.chartData.data[i]?.percent
          }
        }

        let res = ''
        res = `${params.name} : ${target}  (${percentStr})`
        return res
      },
    },
    // 侧面的
    legend: {
      orient: 'vertical',
      top: props.chartData.legend.top,

      left: props.chartData.legend.left || '36%',

      align: 'left',
      itemWidth: changePixelSize(12),
      itemHeight: changePixelSize(12),
      padding: 0,
      itemGap: changePixelSize(10),
      textStyle: {
        color: '#fff', //字体颜色
        rich: {
          a: {
            fontSize: changePixelSize(fontSize),
            lineHeight: changePixelSize(
              props.chartData.legend?.rich?.a?.hasLineHeight
                ? fontSize + 6
                : fontSize
            ),
            borderWidth: 1,
            width: changePixelSize(
              props.chartData.legend?.rich?.a?.width || 78
            ),
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            whiteSpace: 'nowrap',
            align: 'left',
          },
          b: {
            fontSize: changePixelSize(fontSize),
            width: changePixelSize(
              props.chartData.legend?.rich?.b?.width || 95
            ),
            align: 'left',
            fontWeight: 'bold',
          },
          c: {
            fontSize: changePixelSize(fontSize),
            width: changePixelSize(
              props.chartData.legend?.rich?.c?.width || 30
            ),
            align: 'left',
          },
        },
      },
      // 格式化,增加个数和百分比
      formatter: function (name) {
        let ValueStr = ''
        let percentStr = ''
        for (let i = 0; i < props.chartData.data.length; i++) {
          if (props.chartData.data[i].name == name) {
            ValueStr =
              (props.chartData.data[i]?.valueFormat || '') +
              (props.chartData.legend?.suffixHidden
                ? ''
                : props.chartData.data[i]?.suffix)
            percentStr = props.chartData.data[i]?.percent
          }
        }
        let maxLength = language_id.value == 'zh-cn' ? 8 : 12
        if (props.chartData?.legend?.maxLength) {
          maxLength = props.chartData?.legend?.maxLength
        }
        let nameStr =
          name.length > maxLength ? name.substring(0, maxLength) + '...' : name
        // 展示的个数,3是名称 值 百分比 2是名称 值  1是名称
        const showItem = props.chartData?.legend?.showItem || ['a', 'b', 'c']
        let res = ''
        if (showItem.indexOf('a') != -1) {
          if (props.chartData?.legend?.titleWrap) {
            res += '{a|' + nameStr + '\n}'
          } else {
            res += '{a|' + nameStr + '}'
          }
        }
        if (showItem.indexOf('b') != -1) {
          res += '{b|' + ValueStr + '}'
        }
        if (showItem.indexOf('c') != -1) {
          res += '{c|' + percentStr + '}'
        }
        return res
      },
    },
    color: [
      '#1A52B8',
      '#32B16C',
      '#00A0E9',
      '#E6AF08',
      '#87FBF4',
      '#1E49AD',
      '#6054FF',
    ],
    series: [
      {
        name: '',
        type: 'pie',
        stillShowZeroSum: false, // 如果数据和为 0，不显示饼图
        label: {
          show: props.chartData?.series?.show ? true : false, // 如果希望扇形对应的标签也不显示
          color: '#fff',
          position: 'inner', //标签的位置
          fontSize: changePixelSize(fontSize), //文字的字体大小
          formatter: '{d}%',
        },
        labelLine: {
          lineStyle: {
            color: 'rgba(255, 255, 255, 0.3)',
          },
        },
        roseType: props.chartData.roseType,
        radius: props.chartData?.series?.radius || '40%',
        center: props.chartData?.series?.center || ['17%', '50%'],
        data: props.chartData.data.filter((item) => {
          return item.name
        }),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }
  // 绘制图表
  myChart.setOption(option)
}

onMounted(() => {
  setTimeout(() => {
    createChart()
  }, 500)
})

onBeforeUnmount(() => {
  if (myChart && myChart) {
    myChart.dispose()
  }
})
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'bottom-box': chartData.position == 'bottom',
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>
<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(
    260px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
  .chart {
    width: 100%;
    height: 100%;
  }
  .test-btn {
    position: absolute;
    bottom: 0;
    right: 0;
  }
}
.bottom-box {
  height: calc(
    210px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
.dialog-box {
  height: calc(
    500px - 45px
  ); // 45px 是标题 35 高度+10px 轮播图指示器预留空间高度
}
</style>
